package org.cid54.android.jshopper.data.impl;

import android.net.http.AndroidHttpClient;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.cid54.android.jshopper.data.CsvFetcher;

/**
 *
 * @author fgo
 */
public class CsvFetcherImpl implements CsvFetcher {

    //private final String urlString = "http://10.0.2.2:9090/jShopper/mvc/csv/ff1faf79603f443d86b05e772876b604/";
    private final String urlString = "http://gent.dyndns-web.com:9090/jShopper/mvc/csv/ff1faf79603f443d86b05e772876b604/";

    public Boolean postData(String subUrl, Map<String, String> body) {

        try {

            HttpPost post = new HttpPost(urlString + subUrl);

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();

            for (String key : body.keySet()) {

                nvps.add(new BasicNameValuePair(key, body.get(key)));

            }

            post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

            HttpClient client = AndroidHttpClient.newInstance("Android");

            HttpResponse response = client.execute(post);

            return response.getStatusLine().getStatusCode() == 200;

        } catch (Exception ex) {
            ex.getMessage();
        }

        return false;

    }

    public List<String[]> getData(String subUrl) {

        List<String[]> resultL = new ArrayList<String[]>();

        try {

            HttpGet request = new HttpGet(urlString + subUrl);

            HttpClient client = AndroidHttpClient.newInstance("Android");

            HttpResponse response = client.execute(request);

            BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent());

            BufferedReader br = new BufferedReader(new InputStreamReader(bis));

            for (String line = br.readLine(); line != null; line = br.readLine()) {
                resultL.add(line.split(";"));
            }

            br.close();

        } catch (Exception ex) {
            ex.getMessage();
        }

        return resultL;

    }

    public Boolean postData(String subUrl) {
        return this.postData(subUrl, Collections.EMPTY_MAP);
    }
}
